# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
  # See ActionController::RequestForgeryProtection for details
  protect_from_forgery
 
  #Layouts
  layout "main"

  #Helpers
  helper :all # include all helpers, all the time

  #Helper Methods
  helper_method :current_user_session, :current_user

  # Scrub sensitive parameters from your log
  filter_parameter_logging :password, :password_confirmation

  #
  before_filter { |c| Authorization.current_user = @current_user }

  protected

  #Behavior for when a request is made with insignificant
  # privalages
  def permission_denied
    flash[:errors] = "Sorry, you are not allowed to access this page."
    redirect_to root_url
  end

  private

  def current_user_session
    return @current_user_session if defined?(@current_user_session)
    @current_user_session = UserSession.find
  end

  def current_user
    return @current_user if defined?(@current_user)
    @current_user = current_user_session && current_user_session.record
  end

  def require_user
    unless current_user
      store_location
      flash[:notice] = "You must be logged in to access this page"
      redirect_to new_user_session_url
      return false
    end
  end

  def require_no_user
    if current_user
      store_location
      flash[:notice] = "You must be logged out to access this page"
      redirect_to root_url
      return false
    end
  end

  #
  #
  #
  def store_location
    session[:return_to] = request.request_uri
  end

  def redirect_to_request_uri
    uri = session[:return_to]
    session[:return_to] = nil
    redirect_to(uri || root_url)
  end

  def redirect_back_with_artist(id)
    uri = session[:waiting_for]
    session[:waiting_for] = nil
    redirect_to uri + "?artist_select_id=#{id}"
  end

  def store_waiting_for
    session[:waiting_for] = request.request_uri
  end
end
